package com.liuyk.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * @author liuyk
 */
public class ImageHelper {

    /**
     * 打开图库requestCode
     */
    public static void openGallery(Context context, int requestCode) {
        Intent intent;
        //19(4.4)开发者文档推荐写法,但是有些机型并不支持，例如MIUI7.1之前，可以直接打开，7.1之后就只能打开文件管理器
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        } else {
//            intent = new Intent(Intent.ACTION_GET_CONTENT);
        }
        intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        ((Activity) context).startActivityForResult(intent, requestCode);
    }

    /**
     * 两个不同的版本，得到的Uri不同，4.3或以下可以直接用ACTION_GET_CONTENT的,
     * 在4.4或以上,官方建议用ACTION_OPEN_DOCUMENT,主要区别是他们返回的Uri.4.3返回的是带文件路径的,
     * 而4.4返回的却是content://com.android.providers.media.documents/document/image:3951这样的,
     * 没有路径,只有图片编号的uri.可以通过以下方式，处理URI。
     * 参考：Android 4.4从图库选择图片,获取图片路径并裁剪
     *
     * @param activity    应用上下文
     * @param file        裁剪后存放的文件
     * @param uri         系统返回的Uri
     * @param requestCode 系统裁剪requestCode
     */
    public static void doCropPhoto(Activity activity, File file, Uri uri, int requestCode) {
        if (Build.VERSION.SDK_INT >= 19) {
            String dataString = Uri.decode(uri.getPath());
            String id;
            try {//取出id 3591
                id = dataString.substring(dataString.lastIndexOf("/") + 1);
                if (id.contains(":")) {
                    id = id.substring(id.lastIndexOf(":") + 1);
                }
            } catch (Exception e) {
                id = "0";
            }

            String path = getDataColumn(activity, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{id});
            if (TextUtils.isEmpty(path)) {
                path = "";
            }
            File in = new File(path);
            try {
                FileInputStream inFile;
                inFile = new FileInputStream(in);
                FileOutputStream outFile = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int i;
                while ((i = inFile.read(buffer)) != -1) {
                    outFile.write(buffer, 0, i);
                }
                inFile.close();
                outFile.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            uri = Uri.fromFile(file);
        }
        getCropImageIntent(activity, uri, file, requestCode);
    }

    /**
     * 处理4.3之后的Uri
     *
     * @param activity
     * @param uri
     * @return
     */
    public static Uri doUriPhoto(Activity activity, Uri uri) {
        if (Build.VERSION.SDK_INT >= 19) {
            String dataString = Uri.decode(uri.getPath());
            String id;
            try {//取出id 3591
                id = dataString.substring(dataString.lastIndexOf("/") + 1);
                if (id.contains(":")) {
                    id = id.substring(id.lastIndexOf(":") + 1);
                }
            } catch (Exception e) {
                id = "0";
            }

            String path = getDataColumn(activity, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{id});
            if (TextUtils.isEmpty(path)) {
                path = "";
            }
            return Uri.fromFile(new File(path));
        }
        return uri;
    }

    /**
     * 调系统裁剪
     *
     * @param activity    应用上下文
     * @param uri         系统返回的ImageUri
     * @param file        裁剪后存放的文件
     * @param requestCode 系统裁剪requestCode
     */
    public static void getCropImageIntent(Activity activity, Uri uri, File file, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 256);
        intent.putExtra("outputY", 256);
        intent.putExtra("return-data", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        activity.startActivityForResult(intent, requestCode);
    }

    //根据id 查询路径
    private static String getDataColumn(Context context, Uri uri, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, "_id=?", selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

}
